// 供应链智能分析系统 - 导航控制器
class NavigationController {
    constructor() {
        this.currentPage = 'home';
        this.init();
    }

    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupNavigation());
        } else {
            this.setupNavigation();
        }
    }

    setupNavigation() {
        // 设置导航点击事件
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', (e) => this.handleNavClick(e));
        });

        // 监听URL变化
        window.addEventListener('popstate', (e) => this.handlePopState(e));
        
        // 初始化页面
        this.loadPageFromURL();
    }

    handleNavClick(e) {
        e.preventDefault();
        const link = e.target;
        const page = link.getAttribute('data-page');
        
        if (page && page !== this.currentPage) {
            this.navigateToPage(page);
        }
    }

    navigateToPage(page) {
        // 更新当前页面
        this.currentPage = page;
        
        // 更新URL
        const url = new URL(window.location);
        url.searchParams.set('page', page);
        window.history.pushState({ page }, '', url);
        
        // 更新导航状态
        this.updateNavigation();
        
        // 通知Streamlit更新页面
        this.notifyStreamlit(page);
    }

    updateNavigation() {
        // 移除所有活动状态
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => link.classList.remove('active'));
        
        // 添加当前页面的活动状态
        const activeLink = document.querySelector(`[data-page="${this.currentPage}"]`);
        if (activeLink) {
            activeLink.classList.add('active');
        }
    }

    handlePopState(e) {
        if (e.state && e.state.page) {
            this.currentPage = e.state.page;
            this.updateNavigation();
            this.notifyStreamlit(this.currentPage);
        }
    }

    loadPageFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        const page = urlParams.get('page');
        if (page) {
            this.currentPage = page;
            this.updateNavigation();
        }
    }

    notifyStreamlit(page) {
        // 通过postMessage通知Streamlit父窗口
        if (window.parent !== window) {
            window.parent.postMessage({
                type: 'streamlit:setComponentValue',
                value: { page: page }
            }, '*');
        }
        
        // 也可以通过设置隐藏输入框的方式
        const pageInput = document.getElementById('current-page-input');
        if (pageInput) {
            pageInput.value = page;
            pageInput.dispatchEvent(new Event('change'));
        }
    }
}

// 初始化导航控制器
const navController = new NavigationController();

// 导出到全局作用域
window.NavigationController = NavigationController;
window.navController = navController;